package com.java.sample.mac;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * MAC 地址受限于操作系统和 API 很难获取，建议更改方案
 */
public class ArpMacFinder {

    public static String getMacAddressByIp(String ip) throws IOException {
        String os = System.getProperty("os.name").toLowerCase();
        String command;
        String macAddressRegex;

        if (os.contains("win")) {
            // Windows 系统
            command = "arp -a " + ip;
            macAddressRegex = "([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})";
        } else {
            // Linux/MacOS 系统
            command = "arp -n " + ip;
            macAddressRegex = "(([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2})";
        }

        Process process = Runtime.getRuntime().exec(command);
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {

            String line;
            Pattern pattern = Pattern.compile(macAddressRegex);

            while ((line = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    return matcher.group(0).toUpperCase();
                }
            }
        }

        throw new IOException("无法找到IP " + ip + " 对应的MAC地址");
    }

    public static void main(String[] args) {
        try {
            String ip = "127.0.0.1"; // 替换为目标IP
            System.out.println("IP " + ip + " 的MAC地址是: " + getMacAddressByIp(ip));
        } catch (IOException e) {
            System.err.println("错误: " + e.getMessage());
        }
    }
}